package com.bor.gb.db.services;

import com.bor.gb.core.PasswordHash;
import com.bor.gb.core.services.MailService;
import com.bor.gb.core.repo.DataService;
import com.bor.gb.db.domain.Role;
import com.bor.gb.db.domain.User;
import com.bor.gb.core.exception.AppException;
import com.bor.gb.core.exception.UserAlreadyActivatedException;
import com.bor.gb.core.exception.UserNotFoundException;
import com.bor.gb.db.repositories.UserRepository;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class UserService extends DataService<User> {

    private static final Log log = LogFactory.getLog(UserService.class);
    @Autowired
    private MailService mailService;

    @Autowired
    private UserRepository usersRepository;

    @Value("${email.confirmation.enabled}")
    private Boolean notificationEnabled;

    public User createNewUser(String email, String password) {

        log.debug("Creating new user " + email);

        if (usersRepository.findByEmail(email) != null)
            throw new AppException(String.format("User %s already exists", email));

        User user = new User();
        String hash = PasswordHash.createHash(password);
        user.setEmail(email);
        user.setPassword(hash);
        user.setRole(Role.USER);

        user = save(user);

        if (notificationEnabled) {
            user.setLockKey(UUID.randomUUID().toString());
            user = save(user);
            mailService.sendMessage(user.getEmail(), user.getId(), user.getLockKey());
        }
        return user;
    }

    public User unlockUser(String id, String unlockToken){
        User user = usersRepository.findById(id);

        if (user != null) {
            if (user.getLockKey() == null) {
                throw new UserAlreadyActivatedException();
            }
            if (user.getLockKey().equals(unlockToken)) {
                user.setLockKey(null);//unlock
                user = save(user);
                return user;
            } else {
                throw new AppException("Activate key is wrong");
            }

        } else {
            throw new UserNotFoundException();
        }

    }

    public User login(String email, final String password) {
        final User user = usersRepository.findByEmail(email);
        if (user != null) {
            return PasswordHash.validatePassword(password, user.getPassword()) ? user : null;
        }
        return null;
    }

}
